import React, { useEffect } from 'react'
import { useState } from 'react'
import ChevronLeftIcon from '@heroicons/react/24/outline/ChevronLeftIcon'
import ChevronRightIcon from '@heroicons/react/24/outline//ChevronRightIcon'

const Pagination = ({ currentPage, totalCount ,onPageChange,pageSizeList = [],onPageSizeChange }) => {

    const [totalPage, setTotalPage] = useState(0)
    const [pageSize, setPageSize] = useState(10)
    const [toPageIndex, setToPageIndex] = useState(0)

    const iconClasses = `w-10`

    useEffect(() => {
        const totalPage = Math.ceil(totalCount / pageSize)
        setTotalPage(totalPage)
    }, [currentPage, totalCount])

    const goPrev = (page) => {
        if (page < 1 || page > totalPage) return
        onPageChange && onPageChange(page)
    }

    const gotoPageIndex = (e) => {
        if (e.key === 'Enter') {
            if (toPageIndex < 1 || toPageIndex > totalPage) return
            onPageChange && onPageChange(toPageIndex)
        }
    }

    const inputChange = (e) => {
        setToPageIndex(e.target.value)
    }

    const setPageSizeValue = (e) => {
        setPageSize(e.target.value)
        onPageSizeChange && onPageSizeChange( e.target.value)
    }

    return (
        <div className='flex flex-row items-center justify-center my-2'>
            <div className='text-sm mx-4'>共 {totalPage} 页</div>
            {pageSizeList.length > 0 && <div className='text-sm mx-4'>
                <select className='select select-bordered select-sm w-full max-w-xs' value={pageSize} onChange={setPageSizeValue}>
                    {pageSizeList.map((size, index) => <option key={index} value={size}>{size}条/页</option>)}
                </select>
                </div> }
            <div className="join mx-4'">
                <div className="tooltip" data-tip="上一页">
                    <ChevronLeftIcon className={`join-item btn btn-sm ${iconClasses}`} onClick={() => goPrev(currentPage - 1)} />
                </div>
                <div className="join-item btn btn-sm btn-active">{currentPage}</div>
                <div className="tooltip" data-tip="下一页">
                    <ChevronRightIcon className={`join-item btn btn-sm ${iconClasses}`} onClick={() => goPrev(currentPage + 1)} />
                </div>
            </div>
            <div className='text-sm mx-4'>前往
                <input type="number" className='w-10 mx-2 bg-slate-100 text-center' value={toPageIndex} onInput={inputChange} onKeyDown={gotoPageIndex} />
                页
            </div>
        </div>
    )
}

export default Pagination